package com.kerrykidz.system.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.kerrykidz.common.service.ICommonService;
import com.kerrykidz.membership.service.IMemberService;
import com.kerrykidz.system.dao.model.CourseEntity;
import com.kerrykidz.system.dao.model.GblSecBranEntity;
import com.kerrykidz.system.dao.model.KdeBatchEntity;
import com.kerrykidz.system.service.ICourseService;
import com.kerrykidz.system.service.IK3Service;
import com.kerrykidz.system.service.IReportService;
import com.kerrykidz.system.util.DateUtil;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.ReportSearchParam;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.lang.StringUtil;

@RequestMapping("k3")
@Controller
public class K3Controller {
	@Autowired
	IMemberService memService;
	@Autowired
	 IReportService reportService;
	@Autowired
	ICommonService commonService;
	@Autowired
	ICourseService courseService;

	@Autowired
	IK3Service k3Service;

	/**
	 * 跳转到K3对接页面
	 * 
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/findSyncList")
	public ModelAndView sysHoliday(String info) throws RDPException {
		ModelAndView mv = new ModelAndView("system/system_k3_list");
		/**总部不可操作*/
		if(UserUtil.getUserFromSession().getBranId().equals("ZB")){
			mv = new ModelAndView("noAuthority");
			return mv;
		}
		
		setBrank(mv);
		mv.addObject("info", (info != null && info.equals("1") ? info:null));
		return mv;
	}

	@RequestMapping("/findSyncRecord")
	public ModelAndView findSyncRecord(String syncDate) throws RDPException, ParseException {
		ModelAndView mv = null;
		if (syncDate == null) {
			syncDate = DateUtil.formatDate("yyyy-MM-dd", new Date());
		}
		
		/*验证是否存在需要同步的k3数据*/
		String newDate = k3Service.isK3Confirm();
		
		if(StringUtil.isNotBlank(newDate)){
			mv = new ModelAndView("system/system_k3_sync");
		
			/*设置当前用户所属门店*/
			String branId = UserUtil.getUserFromSession().getBranId();
			List<GblSecBranEntity> branList = commonService.getBranListForStock(branId);
			GblSecBranEntity bran = branList.get(0);
			mv.addObject("branName", bran.getBranName());
			mv.addObject("branId", branId);
			
			syncDate = newDate;
			mv.addObject("syncDate", syncDate);
			
			searchByDate(syncDate, mv);
			
		}else{
			mv = new ModelAndView("redirect:/k3/findSyncList.shtml?info=1");
		}
		
		
		return mv;

	}

	/**
	 *  按照日期查询符合条件的数据
	 * @param syncDate
	 * @param mv
	 * @throws RDPException
	 * @date: 2014年11月4日
	 */
	private void searchByDate(String syncDate, ModelAndView mv)
			throws RDPException {
		/**单次票*/
		mv.addObject("singleTicketList", k3Service.findSingleTicket(syncDate));
		
		/** 会籍 */
		// 新增会籍
		mv.addObject("addMemberList", k3Service.findAddMember(syncDate));
		// 会员费分摊
		mv.addObject("avgMemberList", k3Service.findAvgMember(syncDate));
		// 退会
		mv.addObject("retMemberList", k3Service.findRetreatMember(syncDate));

		/** 储值 */
		// 新增储值
		mv.addObject("rechargeList", k3Service.findRecharge(syncDate));
		// 储值消费
		mv.addObject("rcList", k3Service.findRechargeConsume(syncDate));
		// 储值消费退款
		mv.addObject("rcrList", k3Service.findRechargeConsumeRefund(syncDate));
		// 余额退货
		mv.addObject("brList", k3Service.findBalanceRefund(syncDate));
		// 过期余额
		mv.addObject("ebList", k3Service.findExpiredBalance(syncDate));

		/** 派对团体 */
		// 新增预约
		mv.addObject("ppList", k3Service.findPartyPrepay(syncDate));
		//取消预约
		mv.addObject("cancelReservation", k3Service.findCancelRes(syncDate));
		//派对团体结算
		mv.addObject("completedReservation", k3Service.findCompletedRes(syncDate));
		//修改预约
		mv.addObject("updateReservation", k3Service.findPartyUpdate(syncDate));
		
		
		/**课程对接*/
		mv.addObject("newCourseList", courseService.findNewCourese(syncDate));
		mv.addObject("signCourseList", courseService.findSignCourese(syncDate));
		mv.addObject("excendCourseList", courseService.findExceedCourese(syncDate));
		
		/**商品销售*/
		mv.addObject("saleList", courseService.findSaleCommodity(syncDate));
		mv.addObject("returnList", courseService.findReturnCommodity(syncDate));
		
		/**礼券*/
		/*mv.addObject("useCoupon", courseService.findUseCoupon(syncDate));
		mv.addObject("overdueCoupon", courseService.findOverdueCoupon(syncDate));*/
	}

	@RequestMapping("/sync")
	public ModelAndView sync() {
		ModelAndView mv = new ModelAndView("system/system_k3_list");

		return mv;

	}

	/**
	 * 获取金蝶对接批次表，分页展示
	 * 
	 * @param kdeBatch
	 * @return
	 */
	@RequestMapping(value = "/getKdeBatchList", method = RequestMethod.POST)
	@ResponseBody
	public KdeBatchEntity getKdeBatchList(
			@RequestParam(value = "startTimeSearch", required = false) String startTimeSearch,
			@RequestParam(value = "endTimeSearch", required = false) String endTimeSearch,
			KdeBatchEntity kdeBatch) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			if (StringUtil.isNotBlank(startTimeSearch)) {
				kdeBatch.setStartTime(sdf.parse(startTimeSearch + " 00:00:00"));
			}
			if (StringUtil.isNotBlank(endTimeSearch)) {
				kdeBatch.setEndTime(sdf.parse(endTimeSearch + " 23:59:59"));
			}

			if ("-1".equals(kdeBatch.getFkBranId()) || "".equals(kdeBatch.getFkBranId())) {
				kdeBatch.setFkBranId(null);
			}
			if ("-1".equals(kdeBatch.getSyncStatus()) || "".equals(kdeBatch.getFkBranId())) {
				kdeBatch.setSyncStatus(null);
			}
			
			
			
			return k3Service.getKdeBatchList(kdeBatch);
		} catch (RDPException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 确认k3对接
	 * @param kde
	 * @return
	 * @throws RDPException 
	 * @date: 2014年10月29日
	 */
	@RequestMapping(value = "/addK3Dock", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView addK3Dock(@RequestParam("fkBranId")String fkBranId,@RequestParam("confirmTimeStr")String confirmTimeStr) throws RDPException{
		KdeBatchEntity kde = new KdeBatchEntity();
		kde.setFkBranId(fkBranId);
		kde.setConfirmTimeStr(confirmTimeStr);
		
		kde.setFkBranId(fkBranId);
		ModelAndView mv = new ModelAndView("system/system_k3_list");
		kde.setModiBy(UserUtil.getUserFromSession().getUserId());
		kde = k3Service.addK3Docking(kde);
		return mv;
	}
	
	
	private void setBrank(ModelAndView mv) throws RDPException{
		UserInfo userInfo = UserUtil.getUserFromSession();
		String branId = userInfo.getBranId();
		List<GblSecBranEntity> branList = null;
		if (branId.toUpperCase().indexOf("ZB") != -1)// 总部
		{
			branList = commonService.getBranListForStock(null);
			mv.addObject("branList", branList);
			mv.addObject("branId", "-1");
		} else {
			branList = commonService.getBranListForStock(branId);
			mv.addObject("branId", branId);
			mv.addObject("branList", branList);
		}
	}
	
	/**
	 * 导出条码Excel
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping(value="/downLoad",method=RequestMethod.POST)
	public void downLoad(String syncDate,ReportSearchParam reportParam,HttpServletResponse response)throws RDPException{
		if (StringUtil.isBlank(syncDate)) {
			syncDate = DateUtil.formatDate("yyyy-MM-dd", new Date());
		}
		/** 单次票 */
		List<Map<String, Object>> singleTicketList = k3Service.findSingleTicket(syncDate);
		/** 会籍 */
		// 新增会籍
		List<Map<String, Object>> addMemberList = k3Service.findAddMember(syncDate);
		// 会员费分摊
		 List<Map<String, Object>>avgMemberList = k3Service.findAvgMember(syncDate);
		// 退会
		 List<Map<String, Object>> retMemberList = k3Service.findRetreatMember(syncDate);

		//** 储值 *//*
		// 新增储值
		 List<Map<String, Object>> rechargeList = k3Service.findRecharge(syncDate);
		// 储值消费
		 List<Map<String, Object>>rcList = k3Service.findRechargeConsume(syncDate);
		// 储值消费退款
		 List<Map<String, Object>>rcrList = k3Service.findRechargeConsumeRefund(syncDate);
		// 余额退货
		 List<Map<String, Object>> brList = k3Service.findBalanceRefund(syncDate);
		// 过期余额
		 List<Map<String, Object>> ebList = k3Service.findExpiredBalance(syncDate);

		//** 派对团体 *//*
		// 新增预约
		 List<Map<String, Object>> ppList = k3Service.findPartyPrepay(syncDate);
		//更改预约
		 List<Map<String, Object>> updateResData= k3Service.findPartyUpdate(syncDate);
			//取消预约
		 List<Map<String, Object>> cancelResData= k3Service.findCancelRes(syncDate);
		 //派对团体结算
		 List<Map<String, Object>> completedResData=k3Service.findCompletedRes(syncDate);
		
		//**课程对接*//*
		 List<CourseEntity> newCourseList = courseService.findNewCourese(syncDate);
		 List<CourseEntity> signCourseList = courseService.findSignCourese(syncDate);
		 List<CourseEntity> excendCourseList = courseService.findExceedCourese(syncDate);
		
		//**商品销售*//*
		 List<CourseEntity> saleList = courseService.findSaleCommodity(syncDate);
		 List<CourseEntity> returnList = courseService.findReturnCommodity(syncDate);
		
		//**礼券*//*
		 List<CourseEntity> useCoupon = courseService.findUseCoupon(syncDate);
		 List<CourseEntity> overdueCoupon = courseService.findOverdueCoupon(syncDate);
		reportParam.setAddMemberList(addMemberList);
		reportParam.setAvgMemberList(avgMemberList);
		reportParam.setBrList(brList);
		reportParam.setEbList(ebList);
		reportParam.setExcendCourseList(excendCourseList);
		reportParam.setOverdueCoupon(overdueCoupon);
		reportParam.setPpList(ppList);
		reportParam.setUpdateResData(updateResData);
		reportParam.setCancelResData(cancelResData);
		reportParam.setCompletedResData(completedResData);
		reportParam.setRcList(rcList);
		reportParam.setRcrList(rcrList);
		reportParam.setRechargeList(rechargeList);
		reportParam.setRetMemberList(retMemberList);
		reportParam.setReturnList(returnList);
		reportParam.setSaleList(saleList);
		reportParam.setSignCourseList(signCourseList);
		reportParam.setSingleTicketList(singleTicketList);
		reportParam.setUseCoupon(useCoupon);
		reportParam.setNewCourseList(newCourseList);
		reportParam.setReportName("K3Data");
		reportService.barCodeExport(reportParam, response);
	}
	
	@RequestMapping("findK3Info")
	public ModelAndView findK3Info(String syncDate,String batchId) throws RDPException{
		ModelAndView model = new ModelAndView("system/system_k3_info");
		
		/*设置当前用户所属门店*/
		model.addObject("batch", k3Service.findByIdOrDateKdeBatch(batchId, syncDate));
		searchByDate(syncDate, model);
		return model;
	}
}
